package com.kang.service.impl;


import cn.hutool.http.server.HttpServerRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kang.base.LoginDataBase;
import com.kang.entity.SysMenu;
import com.kang.entity.SysUser;
import com.kang.mapper.LoginMapper;
import com.kang.mapper.SysMenuMapper;
import com.kang.mapper.SysUserMapper;
import com.kang.service.LoginService;
import com.kang.util.*;
import com.kang.vo.RouterVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LoginServiceImpl extends ServiceImpl<LoginMapper, SysUser> implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public Map<String,String> adminLogin(SysUser sysUser) throws Exception {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",sysUser.getUsername()).eq("password", AESSimpleUtil.encrypt(sysUser.getPassword())).
                eq("is_deleted",0).eq("type",1);
        SysUser user = baseMapper.selectOne(queryWrapper);

        if (Objects.isNull(user)) {
            throw new Exception("账号或密码错误");
        }
        if (user.getStatus() == 0) {
            throw new Exception("当前账号被禁用");
        }
        Map<String,String> map = new HashMap<>();
        //用户信息存入token中
        String subject = user.getId() + "-" + user.getUsername();
        String token = JwtUtil.createJWT(subject);
        map.put("token",token);
        //用户信息 权限信息 角色名称等存入redis
        LoginDataBase loginDataBase = new LoginDataBase();
        loginDataBase.setUser(user);
        if ("admin".equals(user.getUsername())) {
            loginDataBase.setMenuList(sysMenuMapper.selectList(null));
        } else {
            loginDataBase.setMenuList(sysUserMapper.selectMenuBuUserId(user.getId()));
        }
        loginDataBase.setRoleNameList(sysUserMapper.selectRoleNameByUserId(user.getId()));
        stringRedisTemplate.opsForValue().set("login:token:" + token, JSONObject.toJSONString(loginDataBase),30,TimeUnit.MINUTES);
        return map;
    }

    @Override
    public Boolean layout(String token) {
        return stringRedisTemplate.delete("login:token:" + token);
    }

    @Override
    public Map<String, Object> info(String token) {
        Map<String, Object> resultMap = new HashMap<>();
        String tokenStr = stringRedisTemplate.opsForValue().get("login:token:" + token);
        LoginDataBase loginDataBase = JSONObject.parseObject(tokenStr, LoginDataBase.class);
        assert loginDataBase != null;
        //获取路由地址
        List<SysMenu> sysMenuList = loginDataBase.getMenuList();
        List<SysMenu> buildTree = MenuHelper.buildTree(sysMenuList);
        List<RouterVo> routerVoList = RouterHelper.buildRouters(buildTree);
        //获取按钮权限
        List<String> buttonList = sysMenuList.stream().filter(v -> v.getType() == 2).map(SysMenu::getPerms).collect(Collectors.toList());
        //获取用户信息
        SysUser user = loginDataBase.getUser();
        //获取角色名称
        List<String> roleNameList = loginDataBase.getRoleNameList();
        resultMap.put("name",user.getName());
        resultMap.put("avatar",user.getHeadUrl());
        resultMap.put("roles",JSONObject.toJSON(roleNameList));
        resultMap.put("routers",routerVoList);
        resultMap.put("buttons",buttonList);
        return resultMap;
    }
}
